<template>
	<view class="page">
		<view class="user-box">
			<view class="user" @click="settingUserInfo">
				<up-image :src="avatarUrl" shape="circle" class="avatar" width="112rpx" height="112rpx"></up-image>
				<view class="username">{{ nickName }}</view>
			</view>
			<view class="btn">
				<button class="up-reset-button kefu" open-type="contact">
					<up-image src="https://gamumu.hilumo.com/prod-api/files/down/1950496902787936256.png" width="48rpx" height="48rpx"></up-image>
				</button>
				<up-image src="https://gamumu.hilumo.com/prod-api/files/down/1950497065736646656.png" width="48rpx" height="48rpx" class="setting"
					@click="clickSetting"></up-image>
			</view>
		</view>
		<view class="order-box">
			<!-- 优惠券 -->
			<view class="coupon-box" @click="clickCoupon" v-if="storageData.token">
				<up-image src="https://gamumu.hilumo.com/prod-api/files/down/1950497249837232128.png" class="coupon-icon" width="40rpx"
					height="40rpx"></up-image>
				优惠券
				<up-icon name="arrow-right" size="16" class="coupon-arrow"></up-icon>
			</view>
			<!-- tabs -->
			<view class="tab-box">
				<up-tabs :list="list1" lineWidth="24" lineColor="#D19973" :activeStyle="{
						'color': '#303133',
						'fontWeight': 'bold',
						'transform': 'scale(1.02)'
					}" :inactiveStyle="{
						'color': '#606266',
						'transform': 'scale(1)'
					}" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @click="clickTab">
				</up-tabs>
			</view>
			<!-- 订单 -->
			<view v-if="storageData.token && storageData.token !== ''">
				<scroll-view scroll-y="true" class="scroll-Y" :lower-threshold="50" @scrolltolower="loadMore">
					<view class="orders" v-if="orderData.list.length">
						<view class="order-item" v-for="(item, index) of orderData.list" :key="index" @click="onDetail(item)">
							<view class="img" :style="{ 'backgroundImage': 'url(' + item.coverUrl + '?style=imageMogr2/thumbnail/400x)' }"></view>
							<view class="info">
								<view class="name u-line-1">{{ item.name }}</view>
								<view class="time">{{ timeFormat(new Date(item.createDate).getTime(), 'yyyy-mm-dd hh:MM:ss') }}</view>
								<view class="number">{{ item.uuid }}</view>
								<view class="status" :class="{
									'status1': item.status === 1,
									'status2': item.status === 2,
									'status3': item.status === 3,
									'status4': item.status === 4,
									'status5': item.status === 5}">
									<text v-if="item.status === 1">已支付</text>
									<text v-else-if="item.status === 2">制作中</text>
									<text v-else-if="item.status === 3">已完成</text>
									<text v-else-if="item.status === 4">制作失败</text>
									<text v-else-if="item.status === 5">已退款</text>
								</view>
							</view>
						</view>
						<view style="width: 100%; float: left;">
							<up-loadmore status="nomore" nomore-text="没有更多了" fontSize="12" color="#909399" />
						</view>
					</view>
					<up-empty mode="order" iconColor="#EBEEF5" marginTop="100" v-else></up-empty>
				</scroll-view>
			</view>
			<!-- 立即登录 -->
			<view class="login-btn" v-else>
				<up-button type="primary" shape="circle" color="#E7B796" text="立即登录" @click="handleLogin"></up-button>
			</view>
		</view>
		<!-- 底部Tab -->
		<CustomTabBarVue :selected="2" />
		<!-- 登录弹窗 -->
		<LoginPopup ref="loginPopupRef" @success="handleLoginSuccess" />
	</view>
</template>

<script setup>
	import {
		timeFormat
	} from '@/uni_modules/uview-plus';
	import {
		reactive,
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'
	import CustomTabBarVue from '../../components/CustomTabBar.vue';

	const storageData = reactive({
		token: null,
		user: {}
	})

	// 用户名
	const nickName = computed(() => {
		return storageData.token ? storageData.user.nickName : '未登录'
	})

	// 用户名
	const avatarUrl = computed(() => {
		return storageData.user.avatar && storageData.user.avatar != '' ? storageData.user.avatar :
			'https://gamumu.hilumo.com/prod-api/files/down/1962813547789201408.png'
	})

	const activeTab = ref(999)
	// 创建响应式数据  
	const list1 = reactive([{
			name: '全部',
			value: 999
		},
		{
			name: '已支付',
			value: 1
		},
		{
			name: '制作中',
			value: 2
		},
		{
			name: '已完成',
			value: 3
		},
		{
			name: '制作失败',
			value: 4
		},
		{
			name: '已退款',
			value: 5
		}
	]);

	// 切换tab  
	function clickTab(item) {
		activeTab.value = item.value
		paginationData.value.pageNum = 1
		orderData.list = []
		if (storageData.token && storageData.token !== '') {
			getOrderData()
		}
	}

	// 设置
	function clickSetting() {
		uni.navigateTo({
			url: '/pages/setting/setting'
		})
	}

	// 设置用户信息--头像、昵称
	function settingUserInfo() {
		if (storageData.token && storageData.token !== '') {
			uni.navigateTo({
				url: '/pages/userInfo/userInfo'
			})
		}
	}
	// 优惠券
	function clickCoupon() {
		uni.navigateTo({
			url: '/pages/coupon/coupon'
		})
	}

	// 订单数据
	const orderData = reactive({
		list: [],
		categorys: []
	})
	// 获取订单
	function getOrderData() {
		const params = {}
		if (activeTab.value !== 999) {
			params.status = activeTab.value
		}
		const {
			pageNum,
			pageSize,
			total
		} = paginationData.value
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/pays/mine`,
			method: 'GET',
			header: {
				'Authorization': "Bearer " + storageData.token,
			},
			data: {
				pageNum,
				pageSize,
				...params,
				orderByColumn: 'createDate',
				isAsc: 'desc'
			},
			success: (res) => {
				if (res.data.code === 200) {
					orderData.list = orderData.list.concat(res.data.rows)
					paginationData.value.total = res.data.total
				} else if (res.data.code === 401) {
					uni.removeStorageSync('token')
					uni.removeStorageSync('user')
					uni.removeStorageSync('makeData')
					storageData.token = null
					storageData.user = {}
					uni.showToast({
						icon: 'none',
						title: '已过期，请重新登录'
					})
				}
			},
			fail: (error) => {
				uni.showToast({
					icon: 'none',
					title: '系统开小差了'
				})
			}
		});
	}
	
	// 滑动加载更多
	const paginationData = ref({
		pageNum: 1,
		pageSize: 10,
		total: 0
	})
	function loadMore() {
		const {
			pageNum,
			pageSize,
			total
		} = paginationData.value
		if (pageNum * pageSize < total) {
			paginationData.value.pageNum += 1
			getOrderData()
		}
	}

	// 获取套系分类
	function getDictCatType() {
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/system/dict/data/list`,
			data: {
				dictType: 'template_cat_type',
				pageNum: 1,
				pageSize: 9999
			},
			method: 'GET',
			success: (res) => {
				if (res.data.code === 200) {
					orderData.categorys = res.data.rows
					getOrderData()
				} else if (res.data.code === 401) {
					uni.removeStorageSync('token')
					uni.removeStorageSync('user')
					uni.removeStorageSync('makeData')
					storageData.token = null
					storageData.user = {}
					uni.showToast({
						icon: 'none',
						title: '已过期，请重新登录'
					})
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	// 获取套系分类名称
	function getCatTypeName(value) {
		const arr = orderData.categorys.filter(category => category.dictValue == value)
		return arr.length ? arr[0].dictLabel : '未知'
	}

	// 登录
	const loginPopupRef = ref(null)
	function handleLogin() {
		loginPopupRef.value.open()
	}
	function handleLoginSuccess() {
		initFn()
	}
	
	// 新用户登录
	function registerUser(detail) {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				uni.request({
					url: `${getApp().globalData.baseUrl}/prod-api/wechat/weapp/login`,
					method: 'POST',
					data: {
						code: loginRes.code,
						encrypted_data: detail.encryptedData,
						iv: detail.iv
					},
					success: (res) => {
						if (res.data.code === 200) {
							uni.setStorageSync('token', res.data.token)
							uni.setStorageSync('user', res.data.user)
							initFn()
						}
					},
					fail: (error) => {
						console.log(error);
					}
				});
			}
		});
	}

	// 订单详情
	function onDetail(item) {
		// if (item.status === 3) {
		// 	uni.navigateTo({
		// 		url: `/pages/photo/photo?uuid=${item.uuid}`
		// 	})
		// } else {
		// 	uni.navigateTo({
		// 		url: `/pages/order/detail?uuid=${item.uuid}`
		// 	})
		// }
		uni.navigateTo({
			url: `/pages/order/detail?uuid=${item.uuid}`
		})
	}
	// 初始化执行
	function initFn() {
		storageData.token = uni.getStorageSync('token')
		storageData.user = uni.getStorageSync('user')
		if (storageData.token) {
			getDictCatType()
		}
	}
	onShow(() => {
		orderData.list = []
		paginationData.value.pageNum = 1
		initFn()
	})
</script>

<style lang="scss" scoped>
	.user-box {
		background: url('https://gamumu.hilumo.com/prod-api/files/down/1962785973931388928.png') no-repeat;
		background-size: contain;
		height: 500rpx;
		position: relative;

		.user {
			overflow: hidden;
			position: absolute;
			top: 200rpx;
			left: 46rpx;

			.avatar {
				float: left;
				vertical-align: middle;
				margin-right: 24rpx;
			}

			.username {
				float: left;
				vertical-align: middle;
				line-height: 112rpx;
				font-size: 36rpx;
				font-weight: 500;
			}
		}

		.btn {
			position: absolute;
			top: 236rpx;
			right: 46rpx;

			.kefu,
			.setting {
				display: inline-block;
				margin-left: 30rpx;
			}
		}
	}

	.scroll-Y {
		height: calc(100vh - 640rpx);
	}

	.order-box {
		min-height: calc(100vh - 300rpx);
		border-radius: 40rpx 40rpx 0 0;
		background: #ffffff;
		margin-top: -128rpx;
		padding-top: 20rpx;
		box-sizing: border-box;
		position: relative;

		.orders {
			background: #FEF8F6;
			overflow: hidden;
			padding: 15rpx 28rpx 200rpx;
			.order-item {
				width: 336rpx;
				float: left;
				margin-right: 22rpx;
				margin-bottom: 22rpx;
				padding: 12rpx;
				box-sizing: border-box;
				background-color: #ffffff;
				border-radius: 12rpx;
				&:nth-child(even) {
					margin-right: 0;
				}
				.img {
					display: block;
					width: 312rpx;
					height: 418rpx;
					background-size: 312rpx auto;
					background-repeat: no-repeat;
					background-position: center;
					border-radius: 12rpx;
				}
				.info {
					padding-top: 10rpx;
					position: relative;
					.name {
						font-family: PingFang SC;
						font-weight: 400;
						font-style: Medium;
						font-size: 28rpx;
						leading-trim: NONE;
						line-height: 40rpx;
						color: #333333;
						margin-bottom: 6rpx;
						width: 190rpx;

					}
					.time {
						font-family: PingFang SC;
						font-weight: 400;
						font-style: Regular;
						font-size: 20rpx;
						leading-trim: NONE;
						line-height: 28rpx;
						color: #7F7F7F;
						margin-bottom: 6rpx;
					}
					.number {
						font-family: PingFang SC;
						font-weight: 400;
						font-style: Regular;
						font-size: 20rpx;
						leading-trim: NONE;
						line-height: 28rpx;
						color: #7F7F7F;
					}
					.status {
						position: absolute;
						top: 10rpx;
						right: 12rpx;
						font-family: PingFang SC;
						font-weight: 400;
						font-style: Heavy;
						font-size: 28rpx;
						leading-trim: NONE;
						line-height: 40rpx;
						letter-spacing: 0%;
						text-align: center;
						&.status1 {
							color: #1890ff;
						}

						&.status2 {
							color: #ffba00;
						}

						&.status3 {
							color: #13ce66;
						}

						&.status4 {
							color: #f56c6c;
						}
						&.status5 {
							color: #f56c6c;
						}
					}
				}
			}
		}
	}

	.coupon-box {
		margin: 0 30rpx 20rpx;
		padding: 20rpx;
		background: #f8f8f8;
		border-radius: 12rpx;
		font-size: 28rpx;

		.coupon-icon {
			float: left;
			margin-right: 12rpx;
			margin-top: 2rpx;
		}

		.coupon-arrow {
			float: right;
			margin-top: 2rpx;
		}
	}
	
	.tab-box {
		padding: 0 20rpx 16rpx;
	}
	.login-btn {
		width: 200rpx;
		margin: 300rpx auto;
	}
</style>